import * as fs from 'fs';
import * as path from 'path';
import log from 'electron-log';
import { FileService, FileOperationResult } from './fileService';

// Excel相关接口
export interface ExcelData {
  headers: string[];
  data: any[];
  rawWorkbook?: any;
}

export interface ExcelProcessedData {
  [key: string]: string;
}

// Word相关接口
export interface ReportDataRow {
  reportNo: string;
  labName: string;
  reportDate: string;
}

export interface WordTemplateData {
  rows: Array<{
    type: string;
    reportNo: string;
    labName: string;
    reportDate: string;
    customField: string;
  }>;
}

/**
 * 文档处理日志记录器
 */
class DocumentLogger {
  static info(message: string, ...args: any[]) {
    log.info(`[DocumentService] ${message}`, ...args);
  }

  static warn(message: string, ...args: any[]) {
    log.warn(`[DocumentService] ${message}`, ...args);
  }

  static error(message: string, ...args: any[]) {
    log.error(`[DocumentService] ${message}`, ...args);
  }

  static debug(message: string, ...args: any[]) {
    log.debug(`[DocumentService] ${message}`, ...args);
  }
}

/**
 * 文档错误处理器
 */
class DocumentErrorHandler {
  static handleDocumentError(error: any, operation: string, filePath?: string): FileOperationResult {
    const errorMessage = error?.message || '未知错误';
    const contextMessage = filePath ? `文件路径: ${filePath}` : '';
    
    DocumentLogger.error(`${operation}失败: ${errorMessage}`, contextMessage);
    
    return {
      success: false,
      error: `${operation}失败: ${errorMessage}`
    };
  }

  static handleExcelError(error: any, filePath?: string): FileOperationResult {
    return this.handleDocumentError(error, 'Excel处理', filePath);
  }

  static handleWordError(error: any, filePath?: string): FileOperationResult {
    return this.handleDocumentError(error, 'Word处理', filePath);
  }
}

/**
 * 文档服务类 - 处理Excel和Word文档操作
 */
export class DocumentService {
  private fileService: FileService;
  private pluginsDir: string;

  constructor(fileService: FileService, pluginsDir: string) {
    this.fileService = fileService;
    this.pluginsDir = pluginsDir;
    DocumentLogger.info('DocumentService初始化完成');
  }

  /**
   * 验证Excel文件
   */
  private validateExcelFile(filePath: string): boolean {
    const allowedExtensions = ['.xlsx', '.xls', '.csv'];
    const ext = path.extname(filePath).toLowerCase();
    return allowedExtensions.includes(ext);
  }

  /**
   * 验证Word文件
   */
  private validateWordFile(filePath: string): boolean {
    const allowedExtensions = ['.docx', '.doc'];
    const ext = path.extname(filePath).toLowerCase();
    return allowedExtensions.includes(ext);
  }

  /**
   * 获取Excel表头
   */
  private getExcelHeaders(worksheet: any): string[] {
    const XLSX = require('xlsx');
    const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1');
    const headers: string[] = [];
    
    for (let C = range.s.c; C <= range.e.c; ++C) {
      const cell = worksheet[XLSX.utils.encode_cell({c: C, r: range.s.r})];
      let hdr = cell?.t ? XLSX.utils.format_cell(cell) : `UNKNOWN${C}`;
      headers.push(hdr);
    }
    
    return headers;
  }

  /**
   * 处理Excel数据字段
   */
  private processExcelRow(row: any): ExcelProcessedData {
    const lowercaseFields = [
      '是否单一分包实验室',
      'Assign Sample',
      'Quotation Save',
      'Quotation Generate',
      'Quotation Confirm',
      'Order Confirm',
    ];

    const processedRow: ExcelProcessedData = {};
    
    for (const [key, value] of Object.entries(row)) {
      // 统一处理字符串类型值
      const strValue = typeof value === 'string' ? value.trim() : String(value).trim();
      
      // 对指定字段进行小写转换
      processedRow[key] = lowercaseFields.includes(key) 
        ? strValue.toLowerCase()
        : strValue;
    }
    
    return processedRow;
  }

  /**
   * 读取Excel文件并解析数据
   */
  async readExcelFile(filePath: string): Promise<FileOperationResult> {
    try {
      if (!this.validateExcelFile(filePath)) {
        return { success: false, error: '不支持的Excel文件格式' };
      }

      const XLSX = require('xlsx');
      const workbook = XLSX.readFile(filePath);
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      
      if (!worksheet) {
        return { success: false, error: 'Excel文件中没有找到工作表' };
      }

      const excelData: ExcelData = {
        headers: this.getExcelHeaders(worksheet),
        data: XLSX.utils.sheet_to_json(worksheet),
        rawWorkbook: workbook
      };

      DocumentLogger.info('Excel文件读取成功', { 
        filePath, 
        sheetCount: workbook.SheetNames.length,
        rowCount: excelData.data.length 
      });
      
      return { success: true, data: excelData, filePath };
    } catch (error) {
      return DocumentErrorHandler.handleExcelError(error, filePath);
    }
  }

  /**
   * 读取Excel数据（从Buffer）
   */
  async readExcelData(fileBuffer: ArrayBuffer): Promise<FileOperationResult> {
    try {
      const XLSX = require('xlsx');
      const workbook = XLSX.read(fileBuffer, {type: 'array'});
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      
      if (!worksheet) {
        return { success: false, error: 'Excel文件中没有找到工作表' };
      }

      const rawData = XLSX.utils.sheet_to_json(worksheet, {
        defval: "", // 添加默认值处理
      });

      // 处理数据行
      const processedData = rawData.map((row: any) => this.processExcelRow(row));

      DocumentLogger.info('Excel数据读取成功', { 
        rowCount: processedData.length,
        bufferSize: fileBuffer.byteLength 
      });
      
      return { success: true, data: processedData };
    } catch (error) {
      return DocumentErrorHandler.handleExcelError(error);
    }
  }

  /**
   * 获取Word模板路径
   */
  getWordTemplatePath(pluginName: string): FileOperationResult {
    try {
      const templatePath = path.join(this.pluginsDir, pluginName, `${pluginName}.docx`);
      
      if (!fs.existsSync(templatePath)) {
        return { success: false, error: `Word模板文件不存在: ${templatePath}` };
      }

      if (!this.validateWordFile(templatePath)) {
        return { success: false, error: '不支持的Word文件格式' };
      }

      return { success: true, filePath: templatePath };
    } catch (error) {
      return DocumentErrorHandler.handleWordError(error);
    }
  }

  /**
   * 处理Word文件模板
   */
  async processWordFile(pluginName: string, reportData: ReportDataRow[]): Promise<FileOperationResult> {
    try {
      // 获取模板路径
      const templateResult = this.getWordTemplatePath(pluginName);
      if (!templateResult.success) {
        return templateResult;
      }

      const templatePath = templateResult.filePath!;
      const templateBuffer = fs.readFileSync(templatePath);
      
      // 导入Word处理库
      const Docxtemplater = require('docxtemplater');
      const PizZip = require('pizzip');
      
      const zip = new PizZip(templateBuffer);
      const doc = new Docxtemplater(zip, {
        paragraphLoop: true,
        linebreaks: true
      });

      // 准备模板数据
      const templateData: WordTemplateData = {
        rows: reportData.map((data: ReportDataRow, index: number) => ({
          type: "EU FCM & DGCCRF", // 固定第一列内容
          reportNo: data.reportNo || '', // 第二列报告号
          labName: data.labName || '', // 第三列实验室名称
          reportDate: data.reportDate || '', // 第四列报告日期
          customField: "Report OK", // 第五列固定值
        }))
      };

      // 渲染模板
      doc.render(templateData);
      
      const buffer = doc.getZip().generate({type: 'nodebuffer'});
      
      DocumentLogger.info('Word文件处理成功', { 
        pluginName, 
        templatePath, 
        rowCount: reportData.length,
        bufferSize: buffer.length 
      });
      
      return { success: true, data: buffer, filePath: templatePath };
    } catch (error) {
      return DocumentErrorHandler.handleWordError(error);
    }
  }

  /**
   * 保存Word文件到桌面
   */
  async saveWordFile(buffer: Buffer, filename: string): Promise<FileOperationResult> {
    try {
      if (!this.validateWordFile(filename)) {
        return { success: false, error: '不支持的Word文件格式' };
      }

      return await this.fileService.saveWordFile(buffer, filename);
    } catch (error) {
      return DocumentErrorHandler.handleWordError(error, filename);
    }
  }

  /**
   * 验证文档文件完整性
   */
  async validateDocumentIntegrity(filePath: string): Promise<FileOperationResult> {
    try {
      const ext = path.extname(filePath).toLowerCase();
      
      if (['.xlsx', '.xls'].includes(ext)) {
        // 验证Excel文件
        const XLSX = require('xlsx');
        const workbook = XLSX.readFile(filePath);
        
        if (!workbook.SheetNames || workbook.SheetNames.length === 0) {
          return { success: false, error: 'Excel文件损坏：没有工作表' };
        }
        
        DocumentLogger.info('Excel文件验证通过', { filePath, sheetCount: workbook.SheetNames.length });
        return { success: true, data: { type: 'excel', sheetCount: workbook.SheetNames.length } };
        
      } else if (['.docx', '.doc'].includes(ext)) {
        // 验证Word文件
        const PizZip = require('pizzip');
        const buffer = fs.readFileSync(filePath);
        
        try {
          const zip = new PizZip(buffer);
          // 基本的ZIP结构验证
          const files = zip.files;
          
          if (!files || Object.keys(files).length === 0) {
            return { success: false, error: 'Word文件损坏：ZIP结构无效' };
          }
          
          DocumentLogger.info('Word文件验证通过', { filePath, fileCount: Object.keys(files).length });
          return { success: true, data: { type: 'word', fileCount: Object.keys(files).length } };
          
        } catch (zipError) {
          return { success: false, error: 'Word文件损坏：无法解析ZIP结构' };
        }
        
      } else {
        return { success: false, error: '不支持的文档格式' };
      }
      
    } catch (error) {
      return DocumentErrorHandler.handleDocumentError(error, '文档完整性验证', filePath);
    }
  }

  /**
   * 获取文档信息
   */
  async getDocumentInfo(filePath: string): Promise<FileOperationResult> {
    try {
      const stats = fs.statSync(filePath);
      const ext = path.extname(filePath).toLowerCase();
      
      const info = {
        fileName: path.basename(filePath),
        filePath: filePath,
        fileSize: stats.size,
        fileType: ext,
        createdAt: stats.birthtime,
        modifiedAt: stats.mtime,
        isSupported: this.validateExcelFile(filePath) || this.validateWordFile(filePath)
      };
      
      // 如果是支持的文档格式，获取更多信息
      if (info.isSupported) {
        const validationResult = await this.validateDocumentIntegrity(filePath);
        if (validationResult.success) {
          Object.assign(info, validationResult.data);
        }
      }
      
      DocumentLogger.info('文档信息获取成功', info);
      return { success: true, data: info };
      
    } catch (error) {
      return DocumentErrorHandler.handleDocumentError(error, '获取文档信息', filePath);
    }
  }
}